package org.lanqiao.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.lanqiao.dao.IEleBeforeBillDao;
import org.lanqiao.dao.IEleBeforeCostDao;
import org.lanqiao.dao.IEleUserDao;
import org.lanqiao.myutil.Myutils;
import org.lanqiao.orm.EleBeforeBill;
import org.lanqiao.orm.EleBeforeCost;
import org.lanqiao.orm.EleUser;
import org.lanqiao.service.IOpeatorFun;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service("opService")
public class OpeatorFun implements IOpeatorFun {
	@Resource
	IEleUserDao userDao;
	@Resource
	IEleBeforeCostDao coastDao;
	@Resource
	IEleBeforeBillDao billDao;

	@Override
	public boolean insertUser(EleUser user) {
		// 插入用户的信息
		return userDao.insertUser(user) > 0 ? true : false;
	}

	@Override
	public EleUser selectUser(String card) {
		// 查询用户
		return userDao.selectUser(card);
	}

	@Override
	public float selectCoast(String userid) {
		// 查询需要缴费的金额
		List<EleBeforeCost> lisCoast = coastDao.selectCost(userid);
		// 计算还没有缴费的金额
		int time = lisCoast.size();
		float num = 0;
		for (EleBeforeCost lis : lisCoast) {
			num += lis.getDownmoney();
		}
		return num == 0 ? 0 : num;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { RuntimeException.class, Exception.class })
	public float payMoney(EleUser user, String money, float coast, int opid) {
		// 处理缴费
		float remainBefore = user.getUseradmin();

		float payMoney = Myutils.changeToFloat(money);

		float remainNow = remainBefore + payMoney - coast;
		// 记录这次缴费
		EleBeforeBill bill = new EleBeforeBill();
		bill.setUserid(user.getUserid());
		bill.setUpmoney(coast);
		bill.setOpid(opid);
		billDao.inserPayBill(bill);
		// 把缴费了的表进行更新为已经缴费
		coastDao.updateCoast(user.getUserid());
		return remainNow;
	}

	@Override
	public boolean inserRe(EleUser user, String remain,int opid) {
		//是否把余额存入
		boolean result=false;
		
		EleBeforeBill bill = new EleBeforeBill();
		bill.setUserid(user.getUserid());
		bill.setUpmoney(Myutils.changeToFloat(remain));
		bill.setOpid(opid);
		int i=billDao.inserPayBill(bill);
		//存入余额
		user.setUseradmin(Myutils.changeToFloat(remain));
		int j=userDao.updateredmin(user);
		if(i>0&&j>0){
			result=true;
		}
		return result;
	}

}
